using System;

namespace MathService.Graphs
{
    public class LambdaGraphLink<V, W> : IGraphLink<V, W>
    {
        private readonly IGraphNode<V, W> f_From;
        private readonly Func<V, V, W> f_GetWeight;
        private readonly bool f_Buffered;
        private object f_Weight;
        public IGraphNode<V, W> Node { get; private set; }

        public W Weight
        {
            get
            {
                if(f_Buffered)
                    return (W)(f_Weight ?? (f_Weight = f_GetWeight(f_From.Value, Node.Value)));
                return f_GetWeight(f_From.Value, Node.Value);
            }
        }

        public LambdaGraphLink(IGraphNode<V, W> From, IGraphNode<V, W> To, Func<V, V, W> GetWeight, bool Buffered = false)
        {
            f_From = From;
            f_GetWeight = GetWeight;
            f_Buffered = Buffered;
            Node = To;
        }
    }
}